package main

import (
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"
)

func SimpleGet() {
	resp, err := http.Get("http://127.0.0.1:5656")
	if err != nil {
		fmt.Println(err)
	} else {
		defer resp.Body.Close()
		fmt.Printf("proto: %s\n", resp.Proto)
		fmt.Printf("status: %v\n", resp.Status)
		for k, v := range resp.Header {
			fmt.Printf("%v: %v\n", k, v)
		}
		io.Copy(os.Stdout, resp.Body)
	}
}

func SimplePost() {
	reader := strings.NewReader("i am client")
	resp, err := http.Post("http://127.0.0.1:5656", "text/plain", reader)
	if err != nil {
		fmt.Printf("post error: %v\n", err)
	} else {
		defer resp.Body.Close()
		fmt.Printf("body: ")
		io.Copy(os.Stdout, resp.Body)
	}
}

func PostForm() {
	resp, err := http.PostForm("http://127.0.0.1:5656",
		url.Values{"name": []string{"lwq"}, "addr": []string{"sh"}})
	if err != nil {
		fmt.Println(err)
	} else {
		defer resp.Body.Close()
		fmt.Printf("body: ")
		io.Copy(os.Stdout, resp.Body)
	}
}

func Head() {
	resp, err := http.Head("http://127.0.0.1:5656")
	if err != nil {
		fmt.Println(err)
	} else {
		defer resp.Body.Close()
		fmt.Printf("proto: %s\n", resp.Proto)
		fmt.Printf("status: %v\n", resp.Status)
		for k, v := range resp.Header {
			fmt.Printf("%v: %v\n", k, v)
		}
		io.Copy(os.Stdout, resp.Body)
	}
}

func ComplexRequest() {
	reader := strings.NewReader("i am client in ComplexRequest")
	req, err := http.NewRequest("POST", "http://127.0.0.1:5656/", reader)
	if err != nil {
		fmt.Println(err)
	} else {
		//Header
		req.Header.Add("User-Agent", "6789")
		req.Header.Add("sdfe", "fe3f2")
		//Cookie
		req.AddCookie(&http.Cookie{
			Name:       "pass",
			Value:      "223333",
			Path:       "/",
			Domain:     "localhost",
			Expires:    time.Time{},
			RawExpires: "",
			MaxAge:     0,
			Secure:     false,
			HttpOnly:   false,
			SameSite:   0,
			Raw:        "",
			Unparsed:   nil,
		})
		client := &http.Client{
			Timeout: 3 * time.Second,
		}
		resp, err := client.Do(req)
		if err != nil {
			fmt.Println(err)
		} else {
			defer resp.Body.Close()
			fmt.Printf("====proto: %s\n", resp.Proto)
			fmt.Printf("====status: %v\n", resp.Status)
			fmt.Printf("====header:\n")
			for k, v := range resp.Header {
				fmt.Printf("%v: %v\n", k, v)
			}
			fmt.Printf("====body:\n")
			io.Copy(os.Stdout, resp.Body)
		}
	}
}

func main() {
	//SimpleGet()
	//SimplePost()
	//PostForm()
	//Head()
	ComplexRequest()
}
